package com.huika.dealontop.control.myinfo.activity;

import android.content.Context;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.base.BaseAda;
import com.huika.dealontop.control.myinfo.adapter.MyCouponAdapter;
import com.huika.dealontop.support.domain.MyCouponBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.support.http.rsa.Base64Helper;
import com.huika.dealontop.utils.ClipboardHelper;
import com.huika.dealontop.utils.FileTool;
import com.huika.dealontop.utils.SharpHelper;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.dealontop.views.ToastMsg;
import com.huika.sharpsdklib.Utils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author chenyuan
 * @description：我的优惠券
 * @date 2015年11月16日 上午11:25:04
 */
public class MyCouponActivity extends BaseAct {


    private PullToRefreshListView ptrlv_my_coupon;
    private MyCouponAdapter adapter;
    private PopupWindow popupWindow1;
    private TextView title;
    private TextView right;
    private TextView left;
    private ListView content_lv;
    private int type = 0;
    private View mycoupon_no_content_view;
    private TextView right_tv;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_my_coupon);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        TitleBarHelper titleBarHelper = new TitleBarHelper(this, R.string.common_empty, R.string.my_coupon_screen, R.string.my_coupon_title);
        titleBarHelper.setOnRightClickListener(this);
        right_tv= (TextView) findViewById(R.id.right);
        ptrlv_my_coupon = (PullToRefreshListView) findViewById(R.id.ptrlv_my_coupon);
        mycoupon_no_content_view =  findViewById(R.id.mycoupon_no_content_view);
        findViewById(R.id.my_coupon_btn).setOnClickListener(this);


        adapter = new MyCouponAdapter(this);
        ptrlv_my_coupon.setAdapter(adapter);
//        adapter.setGroup(setData());

        ptrlv_my_coupon.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                CURRENT_PAGE = 1;
                getCouponData();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                CURRENT_PAGE++;
                getCouponData();
            }
        });

        getCouponData();
    }

    private ArrayList<MyCouponBean> setData() {
        ArrayList<MyCouponBean> datas = new ArrayList<MyCouponBean>();
        for (int i = 0; i < 5; i++) {
            MyCouponBean bean = new MyCouponBean();
            bean.vouchersAmount = 10 + i + "";
            bean.giveingDate = "1447828458" + i;
            bean.discountStatus = i + "";
            bean.expiredDate = "1447828458" + i;
            bean.useDate = "1447828458" + i;
            datas.add(bean);
        }
        return datas;
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.right:
                if (popupWindow1 == null) {
                    View view = LayoutInflater.from(this).inflate(R.layout.screen_pop_first, null);
                    initTitle(view);
                    popupWindow1 = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
                    popupWindow1.setAnimationStyle(R.style.pop_in_out);
                    popupWindow1.setOutsideTouchable(true);
//                    view.setOnKeyListener(new MyOnKey());
                }
                popupWindow1.showAtLocation(v, Gravity.RIGHT, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

                break;
            case R.id.my_coupon_btn:
                sharp();
                break;
        }
    }
    private SharpHelper sharpHelper;

    private void sharp() {
        String referralCode = GlobalApp.getInstance().getUserReferralCode();
        if (referralCode == null) {
            referralCode = "";
        }
        if (sharpHelper == null) {
            String title = "DealOnTop";
            String url = getUrl(referralCode);
            String content = getContent(url);
            sharpHelper = new SharpHelper(MyCouponActivity.this,
                    title,
                    url,
                    content,
                    null);

            sharpHelper.setOnClickSharpIconListener(new SharpHelper.OnClickSharpIconListener() {
                @Override
                public void onClickSharp(View view) {
                    if (view.getId() == R.id.iv_sharp_cut) {
                        try {
                            String path = Utils.saveViewToImage(getWindow().getDecorView().findViewById(android.R.id.content));
                            FileTool.refreshAlbum(MyCouponActivity.this, path);
                            Toast.makeText(UIUtils.getContext(), UIUtils.getString(R.string.save_image_to_album), Toast.LENGTH_LONG).show();
                        } catch (Throwable throwable) {
                            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.cut_screen_failure));
                            throwable.printStackTrace();
                        }
                    }
                }
            });

        }
        sharpHelper.show();
    }

    private void initTitle(View v) {
        final CreenAdapter mCreenAdapter = new CreenAdapter(this);
        left = (TextView) v.findViewById(R.id.left);
        title = (TextView) v.findViewById(R.id.title);
        right = (TextView) v.findViewById(R.id.right);
        content_lv = (ListView) v.findViewById(R.id.content_lv);
        content_lv.setAdapter(mCreenAdapter);
        mCreenAdapter.setGroup(getData());
        right.setVisibility(View.VISIBLE);
        title.setVisibility(View.VISIBLE);
        title.setText(getString(R.string.my_coupon_screen));
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closePop();
            }
        });
        content_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                              @Override
                                              public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                  int relPosition = position - content_lv.getHeaderViewsCount();
                                                  if (relPosition >= 0 && relPosition < mCreenAdapter.getCount()) {
                                                      type = relPosition;
                                                      mCreenAdapter.relPos = relPosition;
                                                      mCreenAdapter.notifyDataSetChanged();

                                                      getCouponData();
                                                      Log.d("cy", "" + type);
                                                      closePop();
                                                  }
                                              }
                                          }
        );

    }


    class MyOnKey implements View.OnKeyListener {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                closePop();
            }
            return false;
        }

    }

    private void closePop() {
        if (popupWindow1 != null && popupWindow1.isShowing()) {
            popupWindow1.dismiss();
        }
    }

    private ArrayList<String> getData() {
        ArrayList<String> list = new ArrayList<String>();
        list.add(getString(R.string.my_coupon_all));
        list.add(getString(R.string.my_coupon_no_use));
        list.add(getString(R.string.my_coupon_has_use));
        list.add(getString(R.string.my_coupon_expired));
        return list;
    }

    private void getCouponData() {

        showLoadingDialog(getString(R.string.common_loading));
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        getUserId(ajaxParams);
        ajaxParams.putCommonTypeParam("type", type);//0.全部 1.未使用 2.已使用 3.已过期
        ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
        ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);

        FormResultRequest<ArrayList<MyCouponBean>> getResultRequest = new FormResultRequest<ArrayList<MyCouponBean>>(
                UrlConstants.MEMBERDISCOUNTCOICOUPON, getCouponDataReq, this,
                new TypeToken<RequestResult<ArrayList<MyCouponBean>>>() {
                }.getType());
        getResultRequest.setRequestParams(ajaxParams);
        executeRequest(getResultRequest);

    }

    private void getUserId(JSONWrapAjaxParams ajaxParams) {
        long u_id = GlobalApp.getInstance().getUserId();
        ajaxParams.putCommonTypeParam("userId", u_id);
    }

    private Response.Listener<RequestResult<ArrayList<MyCouponBean>>> getCouponDataReq = new Response.Listener<RequestResult<ArrayList<MyCouponBean>>>() {

        @Override
        public void onResponse(RequestResult<ArrayList<MyCouponBean>> result) {
            if (result.getRs() != null && result.getRs().size() > 0) {
                ptrlv_my_coupon.setVisibility(View.VISIBLE);
                mycoupon_no_content_view.setVisibility(View.GONE);
//                right_tv.setVisibility(View.VISIBLE);
                if (CURRENT_PAGE == 1) adapter.setGroup(result.getRs());
                else adapter.addItems(result.getRs());
                changeRefreshMode(result.getTotalSize());
            }else{
//                right_tv.setVisibility(View.GONE);
                ptrlv_my_coupon.setVisibility(View.GONE);
//                showNoContentView(ptrlv_my_coupon);
                mycoupon_no_content_view.setVisibility(View.VISIBLE);
            }
            dismissLoadingDialog();
            ptrlv_my_coupon.onRefreshComplete();
        }
    };


    private void changeRefreshMode(int totalSize) {
        if (totalSize == 0) {
            ptrlv_my_coupon.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else if (adapter.getCount() >= totalSize) {
            ptrlv_my_coupon.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            ptrlv_my_coupon.setMode(PullToRefreshBase.Mode.BOTH);
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
        super.onErrorResponse(error);
        // enshipLv.onRefreshComplete();
        dismissLoadingDialog();
    }

    private class CreenAdapter extends BaseAda<String> {

        private int relPos;

        public CreenAdapter(Context context) {
            super(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.coupon_pop_item, parent, false);
                vh = new ViewHolder(convertView);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }

            vh.content_tv.setText(getItem(position));
            vh.content_tv.setTextColor(position == relPos ? Color.parseColor("#fe722f") : Color.parseColor("#333333"));
            vh.icon_select_iv.setVisibility(position == relPos ? View.VISIBLE : View.GONE);
            return convertView;
        }

        class ViewHolder {
            public TextView content_tv;
            public ImageView icon_select_iv;

            public ViewHolder(View convertView) {
                content_tv = (TextView) convertView.findViewById(R.id.content_tv);
                icon_select_iv = (ImageView) convertView.findViewById(R.id.icon_select_iv);
            }
        }


    }

    @NonNull
    private String getContent(String url) {
        return UIUtils.getString(R.string.sharp_marked_words) + "," + url;
    }

    private String getUrl(String referralCode) {
        String url = null;
        try {
            url = UrlConstants.HOST + "Register/User?lang=" + UIUtils.getString(R.string.common_lang)
                    + "&shareCode=" + Base64Helper.encode(referralCode.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }


}
